package com.zjb.demo.system.service;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import com.zjb.demo.common.constant.Constants;
import com.zjb.demo.common.constant.UserConstants;
import com.zjb.demo.common.domain.response.TreeSelect;
import com.zjb.demo.common.util.SecurityUtils;
import com.zjb.demo.system.domain.SysMenu;
import com.zjb.demo.system.domain.SysRole;
import com.zjb.demo.system.domain.vo.MetaVo;
import com.zjb.demo.system.domain.vo.RouterVo;
import com.zjb.demo.system.mapper.SysMenuMapper;
import com.zjb.demo.system.mapper.SysRoleMapper;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.zjb.demo.system.domain.table.SysMenuTableDef.SYS_MENU;
import static com.zjb.demo.system.domain.table.SysRoleMenuTableDef.SYS_ROLE_MENU;

/**
 * @author 庄佳彬
 * @since 2023/12/28 18:01
 */
@Component
public class SysMenuService extends ServiceImpl<SysMenuMapper, SysMenu> {

    @Inject
    private SysRoleMapper roleMapper;

    /**
     * 根据角色ID查询对应的菜单权限集合
     *
     * @param roleId 角色ID
     * @return 菜单权限集合
     */
    public Set<String> selectMenuPermsByRoleId(Long roleId) {
        // 通过mapper查询菜单权限列表
        var list = mapper.selectMenuPermsByRoleId(roleId);
        return getPerms(list);
    }

    /**
     * 根据用户ID查询对应的菜单权限列表
     *
     * @param id 用户ID
     * @return 菜单权限列表
     */
    public Set<String> selectMenuPermsByUserId(Long id) {
        var list = mapper.selectMenuPermsByUserId(id);
        return getPerms(list);
    }

    @NotNull
    private static Set<String> getPerms(List<String> list) {
        return list.parallelStream()
                .filter(StrUtil::isNotEmpty)
                .flatMap(item -> Stream.of(item.trim().split(",")))
                .collect(Collectors.toSet());
    }

    /**
     * 根据用户ID选择菜单树
     *
     * @param userId 用户ID
     * @return 菜单树的列表
     */
    public List<RouterVo> selectMenuTreeByUserId(Long userId) {
        List<SysMenu> menus;
        if (SecurityUtils.isAdmin(userId)) {
            menus = mapper.selectMenuTreeAll();
        } else {
            menus = mapper.selectMenuTreeByUserId(userId);
        }
        return buildMenus(getChildPerms(menus, 0));
    }


    private List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        var returnList = new ArrayList<SysMenu>();
        for (SysMenu t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() != parentId) {
                continue;
            }
            recursionFn(list, t);
            returnList.add(t);
        }
        return returnList;
    }

    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        var childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    private List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), Objects.equals("1", menu.getIsCache()), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), false, null));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), false, menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    private String getComponent(SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    private boolean isParentView(SysMenu menu) {
        return Objects.equals(0L, menu.getParentId()) && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    private String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    private String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path,
                new String[]{Constants.HTTP, Constants.HTTPS, Constants.WWW, "."},
                new String[]{"", "", "", "/"});
    }

    private boolean isInnerLink(SysMenu menu) {
        return UserConstants.NO_FRAME.equals(menu.getIsFrame()) && StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS);
    }

    private String getRouteName(SysMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    private boolean isMenuFrame(SysMenu menu) {
        return menu.getParentId().intValue() == 0
                && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame());
    }


    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        return list.stream()
                .filter(n -> n.getParentId().longValue() == t.getMenuId().longValue())
                .toList();
    }

    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return !getChildList(list, t).isEmpty();
    }

    /**
     * 查询菜单列表
     *
     * @param menu 菜单对象
     * @return 菜单列表
     */
    public List<SysMenu> selectMenuList(SysMenu menu) {
        if (SecurityUtils.isAdmin()) {
            return mapper.selectMenuList(menu);
        } else {
            return mapper.selectMenuListByUserId(menu, SecurityUtils.getUserId());
        }
    }

    /**
     * 根据给定的 SysMenu 对象构建 TreeSelect 对象的列表
     *
     * @param menu 给定的 SysMenu 对象
     * @return 树结构的 TreeSelect 对象的列表
     */
    public List<TreeSelect> buildMenuTreeSelect(SysMenu menu) {
        // 获取菜单列表
        var list = selectMenuList(menu);
        // 构建菜单树
        var trees = buildMenuTree(list);
        // 将菜单树转换为 TreeSelect 对象的列表
        return trees.stream()
                .map(TreeSelect::new)
                .toList();
    }


    private List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<>();
        List<Long> tempList = menus.stream().map(SysMenu::getMenuId).toList();
        for (SysMenu menu : menus) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 根据用户ID构建角色菜单树Select列表
     *
     * @return 角色菜单树Select列表
     */
    public List<TreeSelect> buildRoleMenuTreeSelectByUserId() {
        // 获取菜单列表
        List<SysMenu> list = selectMenuList(new SysMenu());
        // 构建菜单树
        var trees = buildMenuTree(list);
        // 将菜单树转换为 TreeSelect 对象的列表
        return trees.stream()
                .map(TreeSelect::new)
                .toList();
    }


    public List<Long> selectMenuListByRoleId(Long roleId) {
        var menuCheckStrictly = roleMapper.selectOneById(roleId)
                .map(SysRole::getMenuCheckStrictly)
                .orElse(false);
        return mapper.selectMenuListByRoleId(roleId, menuCheckStrictly);
    }

    /**
     * 判断是否存在指定的菜单
     *
     * @param menu 要判断的菜单对象
     * @return 如果菜单存在则返回true，否则返回false
     */
    public boolean exists(SysMenu menu) {
        return queryChain()
                .select(SYS_MENU.MENU_ID)
                .from(SYS_MENU)
                .where(SYS_MENU.MENU_NAME.eq(menu.getMenuName()))
                .and(SYS_MENU.PARENT_ID.eq(menu.getParentId()))
                .exists();
    }

    /**
     * 根据菜单ID判断是否存在子菜单
     *
     * @param menuId 菜单ID
     * @return 如果存在子菜单返回true，否则返回false
     */
    public boolean hasChildByMenuId(Long menuId) {
        return queryChain()
                .select(SYS_MENU.MENU_ID)
                .from(SYS_MENU)
                .where(SYS_MENU.PARENT_ID.eq(menuId))
                .exists();
    }


    /**
     * 检查角色是否存在该菜单
     * @param menuId 菜单ID
     * @return 如果角色存在该菜单则返回true，否则返回false
     */
    public boolean checkMenuExistRole(Long menuId) {
        return queryChain()
                .select(SYS_ROLE_MENU.ROLE_ID)
                .from(SYS_ROLE_MENU)
                .where(SYS_ROLE_MENU.MENU_ID.eq(menuId))
                .exists();
    }

}
